<?php
/**
 * Bos 图片上传
 *
 * Author: Zeon
 * Date: 2018/1/27
 * Created by Panxsoft.
 */
namespace App\Http\Controllers\PC;

use App\Http\Controllers\ApiController;
use App\Http\Requests\PC\BosImageUpload\BosImageStoreRequest;
use App\Http\Requests\PC\BosImageUpload\MultiBosImageStoreRequest;
use App\Services\Utils\Bosable;
use Illuminate\Http\UploadedFile;

class BosImageUploadController extends ApiController
{
    use Bosable;

    const DEFAULT_BOS_KEY_PREFIX = 'misc/';

    /**
     * 上传 bos 图片并返回 url
     *
     * @param BosImageStoreRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(BosImageStoreRequest $request)
    {
        $url = $this->uploadFileToUrl($request->image, $request->bos_dir, (bool) $request->keep_name);

        return $this->response(compact('url'));
    }

    /**
     * 上传多张 bos 图片并返回 urls 数组
     *
     * @param MultiBosImageStoreRequest $request
     * @return \Illuminate\Http\Response
     */
    public function storeMulti(MultiBosImageStoreRequest $request)
    {
        $urls = collect($request->images)->map(function (UploadedFile $file) use($request) {
            return $this->uploadFileToUrl($file, $request->bos_dir, (bool) $request->keep_name);
        });

        return $this->response(compact('urls'));
    }

    /**
     * @param UploadedFile $file
     * @param string $dir
     * @param bool $keep_name
     * @return mixed
     * @throws \Exception
     */
    private function uploadFileToUrl(UploadedFile $file, $dir = self::DEFAULT_BOS_KEY_PREFIX, $keep_name = false)
    {
        $bos_key = $this->uploadPostFile($file, $dir, ! $keep_name);

        $url = $this->getStaticUrl($bos_key);

        return $url;
    }


}
